import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Space,
  Image,
  Tag,
  Popconfirm,
  message
} from 'antd'
import styles from './index.module.scss'
import { Link, useHistory } from 'react-router-dom'
import { useEffect, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getArticle, del } from '@/store/actions/login'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { ARTICLE_STATUS } from '@/contants'
import img from '@/assets/error.png'
import Channel from '@/components/Channel'
const { RangePicker } = DatePicker
export default function Article () {
  const history = useHistory()
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getArticle())
  }, [])
  const refParams = useRef({})
  const params = refParams.current
  const {
    results: dataSource, total_count: count, page: current,
    per_page: pageSize
  } = useSelector(
    (state) => state.login.article
  )
  const sumit = ({ status, channel_id: channelId, dateRange }) => {
    // 1.类型。 如果 类型 不是全部，就传给后端参数
    if (status !== -1) {
      params.status = status
    }
    // 2. 频道
    params.channel_id = channelId

    // 3. 日期区间
    if (dateRange) {
      params.begin_pubdate = dateRange[0]
        .startOf('day')
        .format('YYYY-MM-DD HH-mm-ss')
      params.end_pubdate = dateRange[1]
        .endOf('day')
        .format('YYYY-MM-DD HH-mm-ss')
    }
    params.page = 1
    dispatch(getArticle(params))
  }
  const onChange = (page, pagesize) => {
    params.page = page
    dispatch(getArticle(params))
  }
  const onDel = async (id) => {
    try {
      await dispatch(del(id))
      message.success('删除成功')
      dispatch(getArticle(params))
    } catch (error) {
      message.error(error.response.message)
    }
  }
  const edit = (id) => {
    history.push('/home/publish/' + id)
  }
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render (obj) {
        return <Image width={160} height={120} src={obj.images?.[0] || img} />
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '状态',
      dataIndex: 'status',
      render (stu) {
        const status = ARTICLE_STATUS.reduce((acc, item) => {
          acc[item.id] = item
          return acc
        }, {})
        return (<Tag color={status[stu].color}>{status[stu].title}</Tag>)
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count'
    },
    {
      title: '操作',
      key: 'op',
      render (obj, row, index) {
        return (
          <Space>
            <Button type="primary" shape="circle" onClick={() => edit(row.id)} icon={<EditOutlined />} />
            <Popconfirm
              title="你确定要退出本系统吗?"
              okText="确定"
              cancelText="取消"
              placement="bottomRight"
              onConfirm={() => onDel(row.id)}>
             <Button
              type="primary"
              shape="circle"
              danger
              icon={<DeleteOutlined />}
            />
            </Popconfirm>

          </Space>
        )
      }
    }
  ]
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }>
        <Form onFinish={sumit} initialValues={{ status: -1 }}>
          <Form.Item label="状态" name='status'>
            <Radio.Group>
              {ARTICLE_STATUS.map((item) => (
                <Radio key={item.id} value={item.id}>
                  {item.title}
                </Radio>
              ))}
              {/* <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio> */}
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name='channel_id'>
            <Channel/>
          </Form.Item>
          <Form.Item label="日期" name="dateRange">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title={`根据筛选条件共查询到${count}条数据`} >
        <Table pagination={{ total: count, onChange, pageSize, current }} rowKey="id" dataSource={dataSource} columns={columns} />
      </Card>
    </div>
  )
}
